<?php


namespace app\madmin\service;

use app\index\service\CommissionService;
use app\madmin\model\Agent;
use app\madmin\model\AgentBillTemporary;

use app\madmin\model\AgentBillTemporary as admin;
use app\madmin\model\AgentGrade;
use app\madmin\model\CommissionActivity;
use app\madmin\model\CommissionAssessment;
use app\madmin\model\CommissionAssessmentAward;
use app\madmin\model\CommissionAssessmentDegrade;
use app\madmin\model\CommissionAssessmentOrder;
use app\madmin\model\LiveLog;
use app\madmin\model\LiveRoom;
use app\madmin\model\LiveRoomHasGood;
use app\madmin\model\UserCash;
use app\utils\LiveErrorCode;
use app\utils\Wechat;
use think\Console;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\facade\Db;

class CommissionAssessmentService
{
    public function __construct()
    {
        $this->close();
    }

    public function index()
    {

        global $user;
        $mall_id = $user->mall_id;
        $request_data = request()->get();
        $where[] = ['mall_id', '=', $mall_id];
        if ($request_data['start_time']) {
            $where[] = ['create_time', '>', $request_data['start_time']];
            $where[] = ['create_time', '<', $request_data['end_time'] ?? date("Y-m-d", strtotime("+1 day"))];
        }
            
        $data = [
            //累计发放佣金
            'commissions_total' => CommissionAssessment::getCommissions($where),
            //提现成功
            'draw_total' => CommissionAssessment::getAssessmentDraw($where),
            //订单总数
            'order_total' => CommissionAssessment::getOrderCount($where),
            //分销商人数
            'agent_total' => CommissionAssessment::getAgents($where),
            //阶梯佣金人数
            'assessment_agent_total' => CommissionAssessment::getAssessmentAgents($where),
            //降级人数
            'degrades_total' => CommissionAssessment::getDegrades($where),
            //额外阶梯佣金排行
            'assessment_commission_list' => CommissionAssessment::getAssessmentCommission($where),
        ];

        return [HTTP_SUCCESS, $data];
    }


    /**列表
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function list($page, $size)
    {

        global $user;

        $where = [];
        $data = request()->get();
        !empty($data['name']) && $where[] = ['name|content', 'like', '%' . $data['name'] . '%'];
        !empty($data['status']) && $where[] = ['status', '=', $data['status']];
        !empty($data['start_time']) && $where[] = ['start_time', '>=', $data['start_time']];
        !empty($data['end_time']) && $where[] = ['end_time', '<=', $data['end_time']];
        
        $list = CommissionAssessment::where($where)->order('id', 'desc')->paginate(['page' => $page, 'list_rows' => $size]);
        foreach($list as $item){
            $item['total']=count(CommissionAssessment::agents($user->mall_id, $item));
            $where=[["create_time",">",$item->start_time],["create_time","<",$item->end_time],["mall_id",'=',$item->mall_id]];
            $item['commissions_total'] = CommissionAssessment::getCommissions($where);
        }
        return [HTTP_SUCCESS, $list];
    }

    /**详情
     * @param int $id
     * @return int
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     */
    public function detail(int $id)
    {
        $find = CommissionAssessment::find($id);
        return [HTTP_SUCCESS, $find];
    }


    /**添加
     * @param array $data
     * @return array
     */
    public function add()
    {
        list($http, $msg) = $this->checkRole();
        if ($http != 200) {
            return [$http, $msg];
        }



        $data = request()->post();


        $model = new CommissionAssessment();
        $res = $model->create($data);
//        setAttributes($model, $data);
        return [HTTP_SUCCESS, $res];
    }

    /**
     * 删除
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function delete($id)
    {
        $model = CommissionAssessment::where(['id' => $id])->find();
        if (empty($model)) {
            return [HTTP_NOTACCEPT, '删除失败'];
        }
        $model->delete();
        return [HTTP_SUCCESS, $model];
    }

    /**
     * 状态变更
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function status()
    {
        $id = request()->post('id');
        $model = CommissionAssessment::find($id);
        if (!in_array($model->status, [0, 1])) {
            return [HTTP_NOTACCEPT, '只有当活动开始/未开始的才能停止活动'];
        }
        $model->status = 2;
        $model->stop_time=date("Y-m-d H:i:s");
        $model->save();
        return [HTTP_SUCCESS, $model];
    }

    /**订单列表
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function order($page, $size)
    {
//        $this->test();

        $data = request()->get();
        global $user;
        $admin = admin::withoutGlobalScope(['mallId'])->scope('Search', $data)
            ->where("a.mall_id", $user->mall_id)
//            ->where('a.steps', 0)
            ->where('a.is_assessment', 1)
            ->field('a.*');
        
        $list = $admin->paginate(['page' => $page, 'list_rows' => $size]);

        return [HTTP_SUCCESS, $list];
    }

    /**降级列表
     * @param array $data
     * @return array
     * @throws DbException
     */
    public function degrade($page, $size)
    {



        $where = [];
        $data = request()->get();
        !empty($data['name']) && $where[] = ['name', 'like', '%' . $data['name'] . '%'];
        !empty($data['create_time']) && $where[] = ['create_time', '>=', $data['create_time']];
        $res = CommissionAssessmentDegrade::with(["agent",'agentGrade','agentOldGrade'])->where($where)->order('id', 'desc')->paginate(['page' => $page, 'list_rows' => $size]);

        return [HTTP_SUCCESS, $res];
    }

    #开始考核
    public function over_assessment($assessment)
    {

        global $user;
//        $time = date("Y-m-d");
//        $where = [over_assessment
//            ['start_time', '<', $time],
//            ['end_time', '>', $time],
////            ['status','=',1]
//        ];
//        $assessment = CommissionAssessment::where($where)->find();
//        if (empty($assessment)) {
//            return [HTTP_NOTACCEPT, '暂无考核'];
//        }

        $assessment_type = $assessment->assessment_type;
        $level_type=$assessment->level_type;
        $mid = $assessment->mall_id;
        $agent_where[]=['mall_id',"=",$mid];
        if ($level_type==1){
            $levels=json_decode($assessment->levels);
            if(!empty($levels)){
                $agent_where[]=["grade_id",'in',$levels];
            }
        }

        $agents = Agent::where($agent_where)->select();


        $where=[["create_time",">",$assessment->start_time],["create_time","<",$assessment->end_time],["mall_id",'=',$assessment->mall_id]];
        foreach ($agents as $ak => $agent) {
            if ($assessment_type == 0) {
                $assessment_value = CommissionAssessment::getPayment($where);
            } else {
                $assessment_value = CommissionAssessment::getOrderCount($where);
            }

            $orderList=CommissionAssessment::getOrderList($where);

            if($orderList){
                $role_data = json_decode($assessment->role, true);

                $agent_level = $agent['grade_id'];
                foreach ($role_data as $role_info) {
                    if ($role_info['level'] == $agent_level) {

                        $role = $role_info['rule'];

                        $role_count = count($role);
                        for ($i = $role_count - 1; $i >= 0; $i--) {

                            if ($assessment_value >= $role[$i]['min']) {
                                $this->getRate($agent,$orderList,$role[$i]['ladder_commission_rate']);
                            }
                        }
                    }

                }
            }


            #降级
            $this->agent_degrade($assessment, $agent, $assessment_value);
        }

        $assessment->status=3;
        $assessment->stop_time=date('Y-m-d H:i:s');
        $assessment->save();
        return true;
    }

    /**
     * 获取考核奖励中的额外的佣金
     * @param $assessment 考核详情
     * @param $agent 代理
     * @param $pay_price 实际支付金额
     * @param $assessment_value 考核金额
     * @return float|int
     */
    public function getRate($agent,$order_list,$commission_rate)
    {
        $userCashModel=UserCash::where(['user_id'=>$agent->user_id])->find();

        foreach($order_list as $order){
            $pay_price=$order['money'];
            $commission_rate1=number_format($commission_rate / 100, 2);
            $commission = $pay_price * $commission_rate1;
            $data=['commission_rate' => $commission_rate , 'commission' => $commission, 'is_assessment' => 1, 'assessment_status' => 1];

            AgentBillTemporary::update($data,['id'=>$order['id']]);
            if($userCashModel){
                $userCashModel->assessment_total=$userCashModel->assessment_total+$commission;
                $userCashModel->assessment=$userCashModel->assessment+$commission;
                $userCashModel->save();
            }
        }
    }
    public function close(){
        $key="assessment_lock";

        if (Cache::get($key)){

            return false;
        }

        $time = date("Y-m-d H:i:s");
        $where = [
            ['start_time', '<', $time],
            ['end_time', '>', $time],
            ['status', '=', 0]
        ];
        #活动开始的自动变更状态
        CommissionAssessment::update(['status' => 1], $where);
        #活动结束的自动变更
        $over_where = [
            ['end_time', '<', $time],
            ['status', 'in', [0, 1]]
        ];
        $over_list=CommissionAssessment::where($over_where)->select();

        if (count($over_list)>0) {
            $output = \think\facade\Console::call('order_end',[]);
            $output->fetch();
            sleep(1);
            $output = \think\facade\Console::call('agent_get_money',[]);
            $output->fetch();
            sleep(1);
            foreach($over_list as $over_assessment){
                $this->over_assessment($over_assessment);
            }
        }
        Cache::set($key,1,10);

    }
    /**
     * 降级考核
     * @param $role_data 规则
     * @param $agent
     * @param $assessment_value 金额
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function agent_degrade($assessment, $agent, $assessment_value)
    {
        $role_data = json_decode($assessment->role, true);
        $agent_level = $agent->grade_id;
        foreach ($role_data as $role_info) {
            if ($role_info['level'] == $agent_level) {
                #第一步先判断是否有降级策略
                if (!empty($role_info['degrade_min'])) {

                    //不为空则是有降级条件
                    if ($assessment_value < $role_info['degrade_min']) {
                        //降级
                        $grade_id = $agent->grade_id;

                        $next_grade = AgentGrade::where("mall_id", $agent->mall_id)
                            ->where('status', 1)
                            ->where('delete_time', null)
                            ->where('id', '<', $grade_id)
                            ->order('id desc')
                            ->find();

                        if ($next_grade) {
                            $degrade_log_data = [
                                'name' => $assessment->name ?? '',
                                'mall_id' => $agent->mall_id,
                                'level' => $next_grade->id,
                                'old_level' => $agent->grade_id,
                                'agent_id' => $agent->id,
                                'assessment_id' => $assessment->id
                            ];
                            //todo 降级成功写入日志
                            CommissionAssessmentDegrade::write($degrade_log_data);
                            $agent->grade_id = $next_grade->id;
                            $agent->save();
                            return $agent->grade_id;
                        }
                    }
                }
                break;
            }
        }
        return false;
    }

    public function checkRole()
    {
        $data=request()->post();
        $role = $data['role'] ?? [];
        if (empty($role)){
            return [HTTP_SUCCESS, "参数异常"];
        }
        if ($data['end_time'] < $data['start_time']){
            return [HTTP_NOTACCEPT, "结束日期不能低于开始日期"];
        }
        list($code,$msg)=$this->is_exists();
        if($code!=200){
            return [$code,$msg];
        }
        $role_arr = json_decode($role, true);
        foreach($role_arr as $k=>$level_role){
            $role=$level_role['rule'];
            $count=count($role);
            for ($i = $count - 1; $i >= 0; $i--) {
                if ($i == 0) {
                    return [HTTP_SUCCESS, "成功"];
                } else {
                    $condition = $role[$i];
                    $condition1 = $role[$i-1];
                    if ($condition['max']<$condition['min']){
                        if (! ($condition['max']==-1 and ($count-1)==$i)){
                            return [HTTP_NOTACCEPT, "区间最大值必须大于最小值"];
                        }
                    }
                    if ($condition['min']<$condition1['max']){
                        return [HTTP_NOTACCEPT, "阶梯区间必须递增"];
                    }
                }
            }
        }

        return [HTTP_SUCCESS, "成功"];
    }

    public function is_exists(){
        $data=request()->post();
        $model=CommissionAssessment::where([['end_time','>',$data['start_time']],['status','in',[0,1]],['level_type','=',0]])->find();
        if ($model){
            return [HTTP_NOTACCEPT, "已存在考核任务,请先结束考核任务"];
        }

        $where=[['end_time','>',$data['start_time']],['status','in',[0,1]]];

        $assessments = CommissionAssessment::where($where)->select()->toArray();

        $levels=array_column($assessments,'levels');
        $level_arr=[];
        foreach($levels as $item=>$value){
            $level_arr=array_merge($level_arr,json_decode($value));
        }
        $level_ids= array_unique(array_values($level_arr));

        $request_level_data=json_decode($data['levels'],true);

        foreach ($request_level_data as $level){
            if (in_array($level,$level_ids)){
                return [HTTP_NOTACCEPT, "该分销等级已存在考核任务,请先结束考核任务"];
            }
        }
        return [HTTP_SUCCESS, "success"];
    }
}